<?php
	session_start();
	
	function changeURL($path) // hàm chuyển trang với biến truyền vào là $path
	{
		echo '<script type = "text/javascript">';
		echo 'location = "'.$path.'";';
		echo '</script>';
	}
	
	if(isset($_SESSION["MaTaiKhoan"]) == false) // nếu k có session-MaND thì trở về trang index
	{
		changeURL("../trangchu.php");	
	}
	
	include("../template/DataProvider.php"); // import file kết nối CSDL DataProvider.php
	$MaND = $_SESSION["MaTaiKhoan"]; // gán session-MaTaiKhoan vào $MaND
	$ngay = date("Y-m-d");                      
	$query = "SELECT COUNT(*) FROM DonDatHang WHERE NgayDat = '".$ngay."'"; // đếm số lượng đơn đặt hàng
	
	$result = DataProvider::ExecuteQuery($query); 
	$row = mysql_fetch_array($result); 
	if ($row == null)
    {  
		$sosanpham = 0;
    }
	else
		$sosanpham = $row[0] + 1;
     
    
    $SoLuongSP = count($_SESSION["MaSP"]);

    for($i=0; $i < $SoLuongSP; $i++)
    {
        $queryND = " SELECT * from sanpham WHERE MaSP = '".$_SESSION['MaSP'][$i]."' " ;
        $resultND = DataProvider::executeQuery($queryND);
        $rowND = mysql_fetch_array($resultND);
        $MaDDH = date("d").date("m").substr(date("Y"),2,2).date("s".$i).sprintf("%1$03d",$sosanpham); 
        $queryDDH = "INSERT INTO dondathang(MaDDH, NgayDat, TongTien, MaND, MaNguoiBan) VALUES('".$MaDDH."','".$ngay."',0,'".$MaND."', '".$rowND['MaND']."')";
        $resultDDH = DataProvider::ExecuteQuery($queryDDH);

        
            $TongTien = 0;
    		$MaCTDDH = $MaDDH.sprintf("%1$02d",$i); 
    		$soluong = $_SESSION["SoLuong"][$i];  
    		$MaSP = $_SESSION["MaSP"][$i]; 
    		$query = "SELECT GiaSP , SoLuongTon, SoLuongBan FROM sanpham WHERE MaSP = '".$MaSP."'";
    		$result = DataProvider::ExecuteQuery($query);
    		$row = mysql_fetch_array($result);
    		$GiaSP = $row["GiaSP"];
    		       
        		$query = "INSERT INTO chitietddh(MaCTDDH, SoLuong, GiaCa, MaDDH, MaSP, DaThanhToan) VALUES('".$MaCTDDH."',".$soluong.",".$GiaSP.",'".$MaDDH."','".$MaSP."', '0')";
        		DataProvider::ExecuteQuery($query);
        		$soluongton = $row["SoLuongTon"] - $soluong;
        		$soluongban = $row["SoLuongBan"] + $soluong;
        		$query = "UPDATE sanpham SET SoLuongTon = ".$soluongton.", SoLuongBan = ".$soluongban." WHERE MaSP = '".$MaSP."'";
                DataProvider::ExecuteQuery($query);
        		$TongTien += $soluong * $GiaSP;

                
                    $query = "UPDATE DonDatHang SET TongTien = ".$TongTien." WHERE MaDDH = '".$MaDDH."'";
                	DataProvider::ExecuteQuery($query);

                
          
      

    }
        
        
    	

	

        

	unset($_SESSION["MaSP"]); 
	unset($_SESSION["SoLuong"]);   
    echo '<script type="text/javascript">';
    echo 'alert("Đặt hàng thành công! ")';
    echo '</script>';
	changeURL("../trangchu.php");
?>